﻿using Manon.Admin.Web.Application;
using Manon.Admin.Web.Application.Dtos.User;
using Manon.Admin.Web.Common;
using Manon.Core;
using Microsoft.AspNetCore.Mvc;
using Microsoft.IdentityModel.Tokens;
using System.IdentityModel.Tokens.Jwt;
using System.Security.Claims;
using System.Text;

namespace Manon.Admin.Web.Controllers
{
    public class AccountController : Controller
    {
        private readonly ILogger<AccountController> _logger;
        private readonly IUserService _userService;
        public AccountController(ILogger<AccountController> logger, IUserService userService)
        {
            _logger = logger;
            _userService = userService;
        }

        public IActionResult Login()
        {
            return View();
        }


        [HttpPost]
        public async Task<Result<UserLoginOutput>> UserLogin([FromBody] UserLoginInput Input)
        {
            try
            {
                Result<UserOutput> result = await _userService.ValidateUser(Input);

                if (!result.Success) return Result<UserLoginOutput>.Failed(result.Message,null);


                var claims = new ClaimsIdentity(new Claim[]
                   {
                        new Claim("UserId",result.Data.Id.ToString()),
                        new Claim(ClaimTypes.Name,result.Data.UserName),
                        new Claim("RealName",result.Data.RealName.ToString())
                   });
                var key = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(AppSettings.SecretKey));
                var tokenHandler = new JwtSecurityTokenHandler();

                var creds = new SigningCredentials(key, SecurityAlgorithms.HmacSha256);
                var token = new SecurityTokenDescriptor()
                {
                    Issuer = AppSettings.Issuer,
                    Audience = AppSettings.Audience,
                    Subject = claims,

                    Expires = DateTime.Now.AddMinutes(24 * 60),
                    SigningCredentials = creds
                };
                var securityToken = tokenHandler.CreateToken(token);
                return Result<UserLoginOutput>.Successed(result.Message, new UserLoginOutput { Token = tokenHandler.WriteToken(securityToken) });
            }
            catch (Exception ex)
            {
                _logger.LogError("用户登录异常", ex);
                throw;
            }
        }



    }
}


public class UserLoginOutput
{
    public int Code { get; set; }

    public string Token { get; set; }
}